package com.agg.core.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.List;
import java.util.Map;

/**
 * @Auther: ptz
 * @Description:
 */
@Configuration
@Order(2)
public class Beans
        implements ApplicationContextAware {
    private static final Logger log = LogManager.getLogger(Beans.class);
    private static ApplicationContext app;

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        app = applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) {
        return app.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return app.getBean(name, requiredType);
    }

    public static Object getBean(String name) {
        try {
            return app.getBean(name);
        } catch (Exception e) {
        }
        return null;
    }

    public static ApplicationContext getApplicationContext() {
        return app;
    }


    /**
     * 获取实现或者继承某个接口的bean;
     * @param clz
     * @param <T>
     * @return
     */
    public static <T>  Map<String,T> getBeansOfType(Class<T> clz){
        Map<String, T> map = app.getBeansOfType(clz);
        return map;
    }
}
